package com.jy.adscm.operation.purchase.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jy.adscm.bean.system.JyCode;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.exception.AdscmSystemException;
import com.jy.adscm.operation.cgxsb.bean.CgxsCommodityinfo;
import com.jy.adscm.operation.cgxsb.bean.CgxsTaskinfo;
import com.jy.adscm.operation.cgxsb.mapper.mysql.CgxsCommodityinfoMapper;
import com.jy.adscm.operation.cgxsb.mapper.mysql.CgxsTaskinfoMapper;
import com.jy.adscm.operation.config.MyPage;
import com.jy.adscm.operation.purchase.bean.*;
import com.jy.adscm.operation.purchase.mapper.mysql.BomMapper;
import com.jy.adscm.operation.purchase.mapper.mysql.MachinetypeMapper;
import com.jy.adscm.operation.purchase.mapper.mysql.PurchasePlanMapper;
import com.jy.adscm.operation.purchase.service.MachinetypeService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jy.adscm.system.mapper.mysql.JyCodeMapper;
import com.jy.adscm.system.mapper.mysql.JyUserMapper;
import com.jy.adscm.utils.AdscmBaseUtils;
import com.jy.adscm.utils.AdscmDateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 机器型号bom对应数量的配置表 服务实现类
 * </p>
 *
 * @author lzf
 * @since 2019-05-05
 */
@Service
public class MachinetypeServiceImpl extends ServiceImpl<MachinetypeMapper, Machinetype> implements MachinetypeService {
    @Autowired
    BomMapper bomMapper;
    @Autowired
    MachinetypeMapper machinetypeMapper;
    @Autowired
    JyCodeMapper jyCodeMapper;
    @Autowired
    PurchasePlanMapper purchasePlanMapper;
    @Autowired
    CgxsTaskinfoMapper cgxsTaskinfoMapper;
    @Autowired
    CgxsCommodityinfoMapper cgxsCommodityinfoMapper;
    @Autowired
    JyUserMapper jyUserMapper;
    Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public List<Bom> queryByBom(String key) {
        List<Bom> list=null;
        if (AdscmBaseUtils.getInstance().isNotEmpty(key,null)){
            list=bomMapper.queryByLikeBom(key);
        }else {
            list=bomMapper.queryByBom();
        }
        for (Bom bom : list) {
            if (bom.getSpecification() !=null && !"-".equals(bom.getSpecification())){
                bom.setName(bom.getName()+"("+bom.getSpecification()+")");
            }
        }
        return list;
    }

    @Override
    public List<JyCode> queryByMachineType(String type) throws AdscmSystemException {
        Wrapper<JyCode> jyCodeWrapper=new EntityWrapper<>();
        jyCodeWrapper.eq("code_type",type);
        List<JyCode> jyCodes = jyCodeMapper.selectList(jyCodeWrapper);
        if (AdscmBaseUtils.getInstance().isNotEmpty(jyCodes,null)){
            return jyCodes;
        }else {
            throw  new AdscmSystemException("没有查到该类型的码表");
        }
    }

    @Override
    public MyPage<Machinetype> queryConfig(QueryByPageParameter queryByPageParameter,String code) {
        if (queryByPageParameter.getPage()!=0){
            if (queryByPageParameter.getPage()==1){
                queryByPageParameter.setPage(0);
            }else {
                queryByPageParameter.setPage((queryByPageParameter.getPage()-1)*queryByPageParameter.getRows());
            }
        }


        if (AdscmBaseUtils.getInstance().isNotEmpty(queryByPageParameter.getSortBy(),null)){
            queryByPageParameter.setSortBy(queryByPageParameter.getSortBy()+(queryByPageParameter.getDesc() ? " DESC":" ASC"));
        }
        List<Machinetype> list = machinetypeMapper.queryConfig(queryByPageParameter.getPage(), queryByPageParameter.getRows(),
                queryByPageParameter.getKey(), queryByPageParameter.getSortBy(),code);
        Integer count = machinetypeMapper.queryCount(queryByPageParameter.getKey(),code);
        MyPage<Machinetype> myPage=new MyPage<>();
        myPage.setItems(list);
        myPage.setTotal(count);

        return myPage;
    }

    /**
     * 实现思路：前端传过来机器型号、数量、令号、需求日期 通过机器型号 进行关联查询 查询机器bom表 用机器bom表关联 供应商，供应商在关联
     * 供应商与bom表，查询出生产该机器所需要的所有bom和所有关联供应商，通过供应商与bom关联表计算所生成的采购计划表 所需数据
     * @param createPlan
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Integer createPlan(CreatePlan createPlan) throws Exception{

        List<BomAddSupplier> bomAddSuppliers = machinetypeMapper.queryByType(createPlan.getType());
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        Integer total=0;
        if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSuppliers,null)){
            for (BomAddSupplier bomAddSupplier : bomAddSuppliers) {
                PurchasePlan plan=new PurchasePlan();
//                计算需求数量  bom数量*生产机器的台数
                if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getBomNums(),null)){
//                    bomAddSupplier.setNums(bomAddSupplier.getNums()*createPlan.getNum());
                    plan.setNeedNums(bomAddSupplier.getBomNums()*createPlan.getNum());
                }else {
                    throw new AdscmSystemException("机器数量参数有误，请重新输入");
                }
//                设置交货时间
                if (AdscmBaseUtils.getInstance().isNotEmpty(createPlan.getNeedDate(),null)){
                    plan.setDeliveryTime(dateFormat.parse(createPlan.getNeedDate()));
                }

                plan.setMakeNo(createPlan.getMakeNo());
//                下单时间等于 提前到货期+提前采购期
                if (AdscmBaseUtils.getInstance().isNotEmpty(createPlan.getNeedDate(),null)){
                    if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getMaterialLeadTimes(),null)){
                        if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getPredate(),null)){
                            int a=bomAddSupplier.getMaterialLeadTimes()+bomAddSupplier.getPredate();
//                        AdscmDateUtils.getDatePoor(dateFormat.parse(createPlan.getNeedDate(),a);
                            Date date = AdscmDateUtils.dateCount(dateFormat.parse(createPlan.getNeedDate()), a);
                            if (AdscmBaseUtils.getInstance().isNotEmpty(date,null)){
                                plan.setNeedDate(date);
                            }
                        }else {
                            throw new AdscmSystemException("提前采购期不能为空，请检查供应商基础表");
                        }

                    }
                }else {
                    throw new AdscmSystemException("需求日期不能为空");
                }

                if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getMaterialLeadTimes(),null)){
                    Date date = AdscmDateUtils.dateCount(dateFormat.parse(createPlan.getNeedDate()), bomAddSupplier.getMaterialLeadTimes());
                    if (AdscmBaseUtils.getInstance().isNotEmpty(date,null)){
                        plan.setPlanArriveDate(date);
                    }
                }
//                设置付款时间如果是预付款，要增加一个字段，预付款金额要显示出来，付款时间按照付款周期中的时间 进行计算 预计到货时间+付款周期。
//                提货款时间无法计算，是供应商把货做好了就要先打款在发货
//                货到付款 预计到货时间+付款周期中的时间
//                月结 预计到货时间+付款周期中的时间
                if (AdscmBaseUtils.getInstance().isNotEmpty(plan.getNeedDate(),null)&&
                        AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getPaymentPeriod(),null)){
                    if("1".equals(bomAddSupplier.getPaymentMethod())){
                        plan.setPaymentMethod("预付款"+bomAddSupplier.getAdvanceSum()+"%");
                    }else {
                        Wrapper<JyCode> jyCodeWrapper=new EntityWrapper<>();
                        jyCodeWrapper.eq("code_type",6).eq("code",bomAddSupplier.getPaymentMethod());
                        List<JyCode> jyCodes = jyCodeMapper.selectList(jyCodeWrapper);
                        if (AdscmBaseUtils.getInstance().isNotEmpty(jyCodes,null)){
                            plan.setPaymentMethod(jyCodes.get(0).getName());
                        }

                    }
                    Date date = AdscmDateUtils.dateCalculate(plan.getPlanArriveDate(), bomAddSupplier.getPaymentPeriod());
                    plan.setPlanPaymentTime(date);
                }
//                设置货物预计到达日期

//                  库存数量
                if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getBid(),null)){

                    Integer inventoryNums = machinetypeMapper.queryInventoryNums(bomAddSupplier.getBid());
                    if (AdscmBaseUtils.getInstance().isNotEmpty(inventoryNums,null)) {
                        plan.setInventoryNums(Double.valueOf(inventoryNums));
                    }else {
                        plan.setInventoryNums(0.0);
                    }
                }
//                单价
                if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getPrice(),null)){
                    plan.setPrice(bomAddSupplier.getPrice());
                }
//              总价
                if (AdscmBaseUtils.getInstance().isNotEmpty(bomAddSupplier.getPrice(),null)){
                    if (AdscmBaseUtils.getInstance().isNotEmpty(plan.getNeedNums(),null)){
                        plan.setTotal(bomAddSupplier.getPrice()*plan.getNeedNums());
                    }
                }

                plan.setMiniPurchase(bomAddSupplier.getMiniPurchase());
                plan.setBid(bomAddSupplier.getBid());
                plan.setSid(bomAddSupplier.getSid());
                plan.setCreateTime(new Date());
                total = purchasePlanMapper.insert(plan);

            }
        }else {
            throw new AdscmSystemException("机器型号参数有误,无法生成采购计划请核对是否参数有误");
        }
        return total;


    }

    @Override
    public MyPage<PurchasePlan> queryByPlan(String status, QueryByPageParameter queryByPageParameter) {

        MyPage<PurchasePlan> myPage=new MyPage<>();
        Map<String,List<PurchasePlan>> map=new HashMap<>();
        if (queryByPageParameter.getPage()!=0){
            if (queryByPageParameter.getPage()==1){
                queryByPageParameter.setPage(0);
            }else {
                queryByPageParameter.setPage((queryByPageParameter.getPage()-1)*queryByPageParameter.getRows());
            }
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(queryByPageParameter.getSortBy(),null)){
            queryByPageParameter.setSortBy(queryByPageParameter.getSortBy()+(queryByPageParameter.getDesc() ? " DESC":" ASC"));
        }
        List<PurchasePlan> purchasePlans = purchasePlanMapper.queryByPage(queryByPageParameter.getPage(), queryByPageParameter.getRows()
                , queryByPageParameter.getKey(), queryByPageParameter.getSortBy(), null);

        for (PurchasePlan Plan : purchasePlans) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(Plan.getCreateor(),null)){
                JyUser jyUser = jyUserMapper.selectById(Plan.getCreateor());
                if (AdscmBaseUtils.getInstance().isNotEmpty(jyUser.getName(),null)){
                    Plan.setCreateorName(jyUser.getName());
                }
            }
        }
        Integer count = purchasePlanMapper.queryCount(queryByPageParameter.getKey(), null);
        myPage.setTotal(count);
        myPage.setItems(purchasePlans);
        return myPage;
    }



    @Override
    @Transactional
    public Integer updateByPlan(List<PurchasePlan> list) throws AdscmSystemException {
        int result=0;

        for (PurchasePlan plan : list) {
            if (plan.getStatus()==1){
                Wrapper<CgxsTaskinfo> wrapper=new EntityWrapper<>();
//                查询该令号下的供应商有没有在代办采购记录中生成 如果生成直接新增过程记录数据否则新增基础信息+过程记录
                wrapper.eq("makeNo",plan.getMakeNo()).eq("khxx",plan.getSid());
                List<CgxsTaskinfo> cgxsTaskinfos = cgxsTaskinfoMapper.selectList(wrapper);
                if (AdscmBaseUtils.getInstance().isNotEmpty(cgxsTaskinfos,null)&&cgxsTaskinfos.size()>0){
                    CgxsCommodityinfo info=new CgxsCommodityinfo();
                    info.setTid(cgxsTaskinfos.get(0).getTid());
                    info.setSpid(UUID.randomUUID().toString());
                    info.setSpmc(String.valueOf(plan.getBid()));
                    info.setSpjhdj(plan.getPrice());
                    info.setSpjhsl(plan.getNeedNums());
                    info.setPlanarrivedtime(plan.getPlanArriveDate());
                    info.setSpjhsfsj(plan.getPlanPaymentTime());
                    info.setCommodityuse("1");
                    if (AdscmBaseUtils.getInstance().isNotEmpty(plan.getNeedNums(),null)&&
                            AdscmBaseUtils.getInstance().isNotEmpty(plan.getPrice(),null)){
                        info.setSpjhzj(plan.getPrice()*plan.getNeedNums());
                    }else {
                        throw new AdscmSystemException("商品单价或数量不能为空");
                    }

                    info.setSptjsj(new Date());
                    Integer insert = cgxsCommodityinfoMapper.insert(info);
                    if (insert>0){
                        logger.info("采购详细信息新增成功"+insert);
                    }else {
                        logger.info("采购详细信息新增失败了"+insert);
                    }
                }else {
                    String maxOrderNums = cgxsTaskinfoMapper.queryOrderNums();
                    CgxsTaskinfo cgxsTaskinfo=new CgxsTaskinfo();
                    cgxsTaskinfo.setKhxx(String.valueOf(plan.getSid()));
                    int orderNus=1;
                    NumberFormat numberFormat = new DecimalFormat("000");
                    if (AdscmBaseUtils.getInstance().isNotEmpty(maxOrderNums,null)){
                        orderNus=orderNus+Integer.valueOf(maxOrderNums.substring(maxOrderNums.length() - 3));
                    }
                    cgxsTaskinfo.setOrdernums(AdscmDateUtils.getNowOnlyDateFomat2(new Date())+numberFormat.format(orderNus));
                    cgxsTaskinfo.setTid(UUID.randomUUID().toString());
                    SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
                    String trim = format.format(new Date()).replaceAll(":", "").trim().replaceAll("-", "").trim();
//                    if (AdscmBaseUtils.getInstance().isNotEmpty(trim,null)){
//                        cgxsTaskinfo.setTcode(Long.valueOf(trim));
//                    }
                    cgxsTaskinfo.setGoodsname(String.valueOf(plan.getBid()));
                    cgxsTaskinfo.setFbsj(new Date());
                    cgxsTaskinfo.setBzry(plan.getCreateor());
                    cgxsTaskinfo.setRwlx(1);
                    cgxsTaskinfo.setRwzt(0);
                    cgxsTaskinfo.setMakeNo(plan.getMakeNo());
                    cgxsTaskinfo.setNeedDate(plan.getNeedDate());
                    cgxsTaskinfo.setPaymentMethod(plan.getPaymentMethod());
                    Integer addTaskInfo = cgxsTaskinfoMapper.insert(cgxsTaskinfo);
                    if (addTaskInfo>0){
                        logger.info("采购基础表新增成功"+addTaskInfo);
                    }else {
                        logger.info("采购基础表新增失败了"+addTaskInfo);
                    }
                    CgxsCommodityinfo info=new CgxsCommodityinfo();
                    info.setTid(cgxsTaskinfo.getTid());
                    info.setSpid(UUID.randomUUID().toString());
                    info.setSpmc(String.valueOf(plan.getBid()));
                    info.setSpjhdj(plan.getPrice());
                    info.setSpjhsl(plan.getNeedNums());
                    info.setPlanarrivedtime(plan.getPlanArriveDate());
                    info.setSpjhsfsj(plan.getPlanPaymentTime());
                    info.setCommodityuse("1");
                    if (AdscmBaseUtils.getInstance().isNotEmpty(plan.getNeedNums(),null)&&
                            AdscmBaseUtils.getInstance().isNotEmpty(plan.getPrice(),null)){
                        info.setSpjhzj(plan.getPrice()*plan.getNeedNums());
                    }else {
                        throw new AdscmSystemException("商品单价或数量不能为空");
                    }

                    info.setSptjsj(new Date());
                    Integer insert = cgxsCommodityinfoMapper.insert(info);
                    if (insert>0){
                        logger.info("采购详细信息新增成功"+insert);
                    }else {
                        logger.info("采购详细信息新增失败了"+insert);
                    }

                }
            }
            result= purchasePlanMapper.updateById(plan);
        }


        return result;
    }

    @Override
    public List<JyCode> queryMachineList() {
        Wrapper<JyCode> wrapper=new EntityWrapper<>();
        wrapper.eq("code_type",4);
        List<JyCode> jyCodes = jyCodeMapper.selectList(wrapper);
        return jyCodes;
    }

    @Override
    public List<Machinetype> queryByParentId(Long pid,String code) {

        List<Machinetype> list = machinetypeMapper.queryByPid(pid,code);
        if (list!=null && list.size()>0){
            getAllChildren(list);
        }
        return list;
    }

    private void getAllChildren(List<Machinetype> list) {
        for (Machinetype machinetype : list) {
            List<Machinetype> childrens = machinetypeMapper.queryByPid(machinetype.getId(),machinetype.getType());
            if (childrens!=null &&childrens.size()>0){
                getAllChildren(childrens);
            }
            machinetype.setChlidren(childrens);
        }

    }
}
